package com.zerdoor.service.impl;

import com.zerdoor.dao.IRaceInfoDao;
import com.zerdoor.service.ICommonPayService;
import com.zerdoor.service.IRaceInfoService;
import com.zerdoor.util.exception.FeeCardNotEnoughException;
import com.zerdoor.util.exception.InsufficientBalanceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhongjieyu on 2014/11/3.
 * 项目任务-发布悬赏需求 业务层实现类
 */
@Service
public class RaceInfoServiceImpl implements IRaceInfoService {

    @Autowired
    private IRaceInfoDao raceInfoDao;

    @Autowired
    private ICommonPayService commonPayService;

    @Override
    public Map<String, Object> findInitData(int userId) throws Exception {

        //查询需求风格
        List<Map<String, String>> styleList = raceInfoDao.findMinorCodeByMajorid(103);

        //查询需求技能
        List<Map<String, String>> skillList = raceInfoDao.findMinorCodeByMajorid(104);

        //查询增值服务
        List<Map<String, String>> addValue = raceInfoDao.findAddValue();

        //查询零手续费卡数量
        int fee_num = raceInfoDao.findUserFeeNumByUserId(userId);

        Map<String,Object> dataMap = new HashMap<String, Object>();

        dataMap.put("styleList",styleList);
        dataMap.put("skillList",skillList);
        dataMap.put("addValue",addValue);
        dataMap.put("fee_num",fee_num);

        return dataMap;
    }

    @Override
    public List<Map<String, String>> findSkillBySkillIds(String skillIds) throws Exception {


        return raceInfoDao.findSkillBySkillIds(skillIds);
    }

    @Override
    public void addTaskInfoAndAddvalue(Map<String, String> param) throws Exception {

        //插入竞赛信息表
        raceInfoDao.addRaceInfo(param);

        //取出奖项设置字符串
        String racePrizesStr = param.get("racePrizes");

        String[] racePrizes = racePrizesStr.split("&");



        for(int i = 0; i < racePrizes.length; i++){

            Map<String,String> racePrize = getRacePrize(racePrizes[i]);

            racePrize.put("race_id",param.get("race_id"));

            raceInfoDao.addRacePrize(racePrize);

        }


        //插入主订单表
        //raceInfoDao.addOrderMain(param);

        String user_id = param.get("user_id");

        //根据用户id查找推荐人id
        String presenter = raceInfoDao.findPresenterByUserId(user_id);

        //如果推荐人ID为空那么就赋值为-1
        if(presenter == null || "".equals(presenter)){
            presenter = "-1";
        }

        //设置参数
        param.put("presenter",presenter);

        //查询增值服务总价
        String addvalueSumPrice = "0";

        if(param.get("addvalue_ids") != null && !"".equals(param.get("addvalue_ids"))){
            addvalueSumPrice = raceInfoDao.findAddvalueSumPriceByAddvalueIds(param.get("addvalue_ids"));
        }
        //设置参数
        param.put("addvalue",addvalueSumPrice);

        //插入任务订单表
        raceInfoDao.addOrderRace(param);


        //取出增值服务ID集合
        String[] addvalue_ids = param.get("addvalue_ids").split(",");

        //循环插入增值服务数据
        for(String addvalue_id : addvalue_ids){

            if(!"".equals(addvalue_id)){
                param.put("addvalue_id",addvalue_id);

                raceInfoDao.addOrderAddvalue(param);
            }

        }



    }

    /**
     * 解析奖项字符串返回奖项map
     * @param racePrizesStr
     * @return
     * @throws Exception
     */
    private Map<String,String> getRacePrize(String racePrizesStr) throws Exception{

        Map<String,String> racePrize = new HashMap<String,String>();

        String[] tempStr = racePrizesStr.split(",");

        for(int j = 0; j < tempStr.length; j++){

            String[] str = tempStr[j].split("=");

            if("name".equals(str[0])){

                if(str.length == 2){

                    racePrize.put("name",str[1]);
                }else{
                    racePrize.put("name","");
                }
            }
            if("num".equals(str[0])){

                if(str.length == 2){

                    racePrize.put("num",str[1]);
                }else{
                    racePrize.put("num","");
                }
            }
            if("money".equals(str[0])){

                if(str.length == 2){

                    racePrize.put("money",str[1]);
                }else{
                    racePrize.put("money","");
                }
            }

        }

        return racePrize;
    }

    @Override
    public void updateItemInfoByItemId(Map<String, String> param) throws Exception {


        //修改项目信息
        raceInfoDao.updateRaceInfoByRaceId(param);

        //根据竞赛活动ID删除奖项
        raceInfoDao.deleteRacePrize(param.get("race_id"));

        //取出奖项设置字符串
        String racePrizesStr = param.get("racePrizes");

        String[] racePrizes = racePrizesStr.split("&");


        for(int i = 0; i < racePrizes.length; i++){

            Map<String,String> racePrize = getRacePrize(racePrizes[i]);

            racePrize.put("race_id",param.get("race_id"));

            //插入奖项
            raceInfoDao.addRacePrize(racePrize);

        }

        //得到任务订单ID
        String order_race_id = raceInfoDao.findOrderTaskIdByRaceId(param.get("race_id"));

        //查询增值服务总价
        String addvalueSumPrice = "0";

        if(param.get("addvalue_ids") != null && !"".equals(param.get("addvalue_ids"))){
            addvalueSumPrice = raceInfoDao.findAddvalueSumPriceByAddvalueIds(param.get("addvalue_ids"));
        }

        //设置参数
        param.put("order_race_id",order_race_id);
        param.put("addvalue",addvalueSumPrice);

        //修改任务订单增值服务
        raceInfoDao.updateOrderTaskAddvalueById(param);

        //根据任务订单ID删除增值服务数据
        raceInfoDao.deleteOrderItemAvByOrderTaskId(order_race_id);


        //取出增值服务ID集合
        String[] addvalue_ids = param.get("addvalue_ids").split(",");

        //循环插入增值服务数据
        for(String addvalue_id : addvalue_ids){

            if("".equals(addvalue_id)){
                continue;
            }

            param.put("addvalue_id",addvalue_id);

            raceInfoDao.addOrderAddvalue(param);
        }



    }

    @Override
    public Map<String, Object> updateFindTaskInfoByTaskId(String raceId) throws Exception {

        //
        Map<String, Object> map = raceInfoDao.findRaceInfoByRaceId(raceId);



        if(map != null){

            //增值服务
            List<Map<String, String>> list = raceInfoDao.findOrderAddvalueByRaceId(raceId);
            map.put("addvalues",list);

            //奖项
            List<Map<String,String>> racePrizeList =  raceInfoDao.findRacePrizeByRaceId(raceId);
            map.put("racePrizeList",racePrizeList);

            //如果需求技能ID集不为空，那么就进行翻译处理
            if(map.get("skill") != null && !"".equals(map.get("skill").toString())){

               map.put("skill",raceInfoDao.findSkillNameBySkillIds(map.get("skill").toString()));
            }



            //放入增值服务费用总计
            float sumAddvalue = 0.0f;
            for(Map<String, String> addMap : list){

                sumAddvalue += Float.parseFloat(addMap.get("price"));

            }
            map.put("sumAddvalue",sumAddvalue);

            //放入奖项费用总计
            float sumPrize = 0.0f;
            for(Map<String, String> prizeMap : racePrizeList){

                sumPrize += Float.parseFloat(prizeMap.get("money")) * Integer.parseInt(prizeMap.get("num"));

            }
            map.put("sumPrize",sumPrize);

            Map progress = new HashMap();
            progress.put("race_id",raceId);
            progress.put("progress","128102");
            //改变任务状态为发布项目
            raceInfoDao.updateCurrentProgressByTaskId(progress);

        }

        return map;
    }

    @Override
    public Map<String,Object> updateFindAddvalueByTaskId(String raceId,String userId) throws Exception {

        Map<String,Object> dataMap = new HashMap<String, Object>();

        //项目进度
        Map itemInfo = raceInfoDao.findRaceById(raceId);

        //放入奖项费用总计
        float sumPrize = 0.0f;
        int progress = (Integer) itemInfo.get("progress");
        if(128104 > progress){

            //奖项
            List<Map<String,String>> racePrizeList =  raceInfoDao.findRacePrizeByRaceId(raceId);

            for(Map<String, String> prizeMap : racePrizeList){

                sumPrize += Float.parseFloat(prizeMap.get("money")) * Integer.parseInt(prizeMap.get("num"));

            }

        }

        //查询增值服务
        float addvSumPrice = 0.0f;
        List<Map<String, String>> addvList = raceInfoDao.findOrderAddvalueByRaceId(raceId);
        for(Map<String, String> map : addvList){

            addvSumPrice += Float.parseFloat(map.get("price"));

        }

        //支付总金额
        float totalAmount = sumPrize + addvSumPrice;

        //查询账户余额
        float wallet = raceInfoDao.findUserWalletById(userId);

        dataMap.put("title",itemInfo.get("title"));
        dataMap.put("totalAmount",totalAmount);
        dataMap.put("wallet",wallet);

        Map progressMap = new HashMap();
        progressMap.put("race_id",raceId);
        progressMap.put("progress","128103");
        //改变任务状态为托管定金
        raceInfoDao.updateCurrentProgressByTaskId(progressMap);

        return dataMap;
    }

    @Override
    public boolean isRaceInfoProgress(String raceId) throws Exception {

        //项目进度
        Map itemInfo = raceInfoDao.findRaceById(raceId);

        int progress = (Integer) itemInfo.get("progress");
        if(progress > 128103){
            return false;
        }

        return true;

    }

    @Override
    public boolean addvaluePayByAlipay(String race_id,String user_id) throws Exception {


        return false;
    }

    @Override
    public boolean addvaluePayByPaypay(String race_id,String user_id) throws Exception {


        return false;
    }

    @Override
    public Map<String,Object> addvaluePayByBalance(String race_id,String user_id) throws Exception {

        //返回数据Map
        Map<String,Object> dataMap = new HashMap<String, Object>();

        //项目进度
        Map raceInfo = raceInfoDao.findRaceById(race_id);

        //放入奖项费用总计
        float sumPrize = 0.0f;
        int progress = (Integer) raceInfo.get("progress");
        if(128103 != progress){


            dataMap.put("static","4");
            dataMap.put("msg","该竞赛活动已进入审核阶段，不能再支付费用了！");

            return dataMap;

        }

        //奖项
        List<Map<String,String>> racePrizeList =  raceInfoDao.findRacePrizeByRaceId(race_id);

        for(Map<String, String> prizeMap : racePrizeList){

            sumPrize += Float.parseFloat(prizeMap.get("money")) * Integer.parseInt(prizeMap.get("num"));

        }

        //查询增值服务
        float addvSumPrice = 0.0f;
        List<Map<String, String>> addvList = raceInfoDao.findOrderAddvalueByRaceId(race_id);
        for(Map<String, String> map : addvList){

            addvSumPrice += Float.parseFloat(map.get("price"));

        }

        //支付总金额
        float totalAmount = sumPrize + addvSumPrice;

        //放入项目名
        dataMap.put("title",raceInfo.get("title"));

        //根据竞赛活动查询订单信息
        Map orderRaceMap = raceInfoDao.findOrderRaceByRaceId(race_id);

        //得到竞赛活动ID
        int order_race_id = Integer.parseInt(String.valueOf(orderRaceMap.get("order_race_id")));

        //查询用户账户是否充足
        boolean enoughFlag = commonPayService.isUserWalletEnough(totalAmount,Integer.parseInt(user_id));

        //如果为false 表示用户账户余额不足
        if(!enoughFlag){

            throw new InsufficientBalanceException("支付失败，账户余额不足或金额被冻结，抛出自定义异常!用户ID："+ user_id + "；支付金额：" + addvSumPrice +"；支付类型：" + 112112);
        }

        //支付 类型：112112 表示增值服务支出
        boolean payFlag = commonPayService.updateDeductUserWalletByUserId(addvSumPrice,Integer.parseInt(user_id),112112);

        //如果支付标识为false 那么就表示没有支付成功
        if(!payFlag){

            throw new InsufficientBalanceException("支付失败，账户余额不足，抛出自定义异常!用户ID："+ user_id + "；支付金额：" + addvSumPrice +"；支付类型：" + 112112);
        }

        //冻结，类型：112110 表示冻结金额
        boolean blockedFlag = commonPayService.updateBlockedUserWalletByUserId(sumPrize,Integer.parseInt(user_id),112110,order_race_id,false,false);

        if(!blockedFlag){

            throw new InsufficientBalanceException("支付失败，账户余额不足，抛出自定义异常!用户ID："+ user_id + "；支付金额：" + sumPrize +"；支付类型：" + 112110);
        }



        //查询是否使用手续费卡，手续费卡是否充足，如果充足就扣掉手续费卡，并且写入竞赛活动订单表；


        //放入总金额
        orderRaceMap.put("total_price",sumPrize);

        if(raceInfo.get("use_fee") == null ){
            raceInfo.put("use_fee",101002);
        }


        int use_fee = Integer.parseInt(String.valueOf( raceInfo.get("use_fee")));

        //101001 为是
        if(101001 == use_fee){

            //查询手续费卡数量
            int feeNum = raceInfoDao.findUserFeeNumByUserId(Integer.parseInt(user_id) );

            if(feeNum > 0){

                //扣除用户当前手续费卡
                raceInfoDao.updateUserFeeNumByUserId(user_id);

                //手续费使用记录Map
                Map user_feeMap = new HashMap();

                user_feeMap.put("user_id",user_id);
                user_feeMap.put("num",1);
                user_feeMap.put("type",132103);
                //需要得到竞赛订单ID
                user_feeMap.put("remark","消耗零手续费卡，竞赛活动订单ID：" + orderRaceMap.get("order_race_id"));

                //写入0手续费卡使用记录
                raceInfoDao.insertUserFee(user_feeMap);

                //放入主订单手续费
                orderRaceMap.put("fee",0);

            }else{

                throw new FeeCardNotEnoughException("零手续费卡不足，抛出自定义异常！用户ID："+ user_id + "，竞赛活动订单ID：" + orderRaceMap.get("order_race_id"));

            }

        }else{

            //查询竞赛活动手续费百分比，4为固定ID
            float scaleValue = commonPayService.findScaleValue(4);

            //手续费
            float fee = sumPrize * scaleValue / 100;

            //放入主订单手续费
            orderRaceMap.put("fee",fee);

        }

        //查询是否有推荐者，如果是那么查询该推荐者是否首次推荐，如果是那么就维护相应的推广费
        String presenter = String.valueOf(orderRaceMap.get("presenter"));

        //初始化推荐状态
        boolean presenterFlag = false;

        //-1表示没有推荐者
        if(!"-1".equals(presenter)){

            //查询是否首次发包推广
            int ispoSender = raceInfoDao.findUserIspoSenderByPresenter(user_id);

            if(101001 == ispoSender){

                //查询竞赛活动推广费百分比，5为固定ID
                float scaleValue = commonPayService.findScaleValue(5);

                //推广费
                float popur = sumPrize * scaleValue / 100;

                //放入主订单推广费
                orderRaceMap.put("popur",popur);

                //修改推荐者首次推广状态
                raceInfoDao.updateUserIspoSenderByPresenter(user_id);

                presenterFlag = true;


            }

        }

        //推荐状态为false 表示没有推广费
        if(!presenterFlag){

            //放入主订单推广费
            orderRaceMap.put("popur",0);
        }

        //根据竞赛活动ID更新竞赛活动部分缺失数据
        raceInfoDao.updateOrderRaceById(orderRaceMap);

        for(Map<String,String> addvalue : addvList){

            //改变增值服务状态和价格
            raceInfoDao.updateOrderAddvalueStatus(addvalue);
        }


        Map progressMap = new HashMap();
        progressMap.put("race_id",race_id);
        progressMap.put("progress","128104");

        //改变任务状态为审核中
        raceInfoDao.updateCurrentProgressByTaskId(progressMap);


        dataMap.put("static","0");
        dataMap.put("msg","支付成功！");

        return dataMap;

    }

}
